/*
 * Project: book
 * 
 * File Created at 2017年9月12日
 * 
 * Copyright 2016 CMCC Corporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ZYHY Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license.
 */
package com.whb.book.common.encDec;

import java.util.Random;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/**
 * @Type Aes.java
 * @Desc 
 * @author wanghb
 * @date 2017年9月12日 下午12:56:11
 * @version 
 */
public class Aes {

    private final static String ALGO = "AES";

    private static final Random r = new Random();

    public static String genKey() throws Exception {
        byte[] b = new byte[16];
        r.nextBytes(b);
        return Base64.encodeBase64String(b);
    }

    /**
     * 
     * decByAes:(). <br/>
     * 
     * 
     * @author wanghb
     * @param data
     * @param key
     * @return
     * @throws Exception
     * @since JDK 1.8
     */
    public static byte[] decByAes(byte[] data, String key) throws Exception {
        SecretKey deskey = new SecretKeySpec(Base64.decodeBase64(key), ALGO);
        Cipher cipher = Cipher.getInstance(ALGO);
        cipher.init(Cipher.DECRYPT_MODE, deskey);
        return cipher.doFinal(data);
    }

    /**
     * 
     * encByAes:(). <br/>
     * 
     * 
     * @author wanghb
     * @param data
     * @param key
     * @return
     * @throws Exception
     * @since JDK 1.8
     */
    public static byte[] encByAes(byte[] data, String key) throws Exception {
        SecretKey deskey = new SecretKeySpec(Base64.decodeBase64(key), ALGO);
        Cipher cipher = Cipher.getInstance(ALGO);
        cipher.init(Cipher.ENCRYPT_MODE, deskey);
        return cipher.doFinal(data);
    }

    public static void main(String[] args) throws Exception {
        // 长度16，24，32字节
        String AES_KEY = genKey();
        String word = "王弘博王弘博王弘博王弘博";
        System.out.println("AES密钥:" + AES_KEY);
        System.out.println("AES密钥字节长度:" + Base64.decodeBase64(AES_KEY).length);
        byte[] bytes = encByAes(word.getBytes(), AES_KEY);
        System.out.println("--" + bytes.length);
        String encWord = Base64.encodeBase64String(bytes);
        System.out.println("加密后：" + encWord);
        System.out.println("解密后：" + new String(decByAes(bytes, AES_KEY)));
    }


}


/**
 * Revision history
 * -------------------------------------------------------------------------
 * 
 * Date Author Note
 * -------------------------------------------------------------------------
 * 2017年9月12日 wanghb create
 */